package threadPool.ThreadFactory;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 在线程线程创建过程中捕获线程运行时异常
 */
public class MyExceptionThreadFactory implements ThreadFactory {
    private String factoryName;
    private boolean saveLog;
    public MyExceptionThreadFactory(String factoryName, boolean saveLog) {
        this.factoryName = factoryName;
        this.saveLog = saveLog;
    }

    @Override
    public Thread newThread(Runnable r) {
        if(saveLog){
            // 动态日志输出
            System.out.println(System.currentTimeMillis() + this.factoryName + " create start");
        }
        Thread thread = new Thread(r);
        // 自定义线程名字
        thread.setName("Kevin-Thread-" + thread.getName() + ":" + thread.getId());
        thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler(){
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                System.out.println(t.getName() + " exception " + e.getMessage() );
                e.printStackTrace();
            }
        });
        if(saveLog){
            System.out.println(System.currentTimeMillis()+ this.factoryName + " "
             + thread.getName() + " create end");
        }
        return thread;
    }

}
